<?php
/*
 * 资讯频道模型管理
 */
class ZixunchannelAction extends CommonAction{
    
    /*
     * 模型列表
     */
    public function index(){
        $m = M('Zixunchannel');
        $list = $m->select();
        $this->assign('list',$list);
        $this->display();
    }
    
    /*
     * 模型增加
     */
    public function add(){
        $m = D('Zixunchannel');
        if(IS_POST){ 
            /*如果选择的是自动模型与系统模型则增加一些固化的字段*/
            $data = I('post.');
            if($data['modeltype'] == 3){
                $sql = 'create table '.C('DB_PREFIX').$data['tablename'].'(typeid int(11) comment "所属栏目")';
            }else{
                $sql = 'create table '.C('DB_PREFIX').$data['tablename'].'(aid int(11) comment "文章ID" primary key,typeid int(11) comment "所属栏目")';
            }
            $is_table = $this->is_table($data['tablename']);
            if($is_table){$this->error('数据库中已经存在 '.$data['tablename'].' 表');}
            if(false === $m->create()){$this->error($m->getError());}            
            if(false === $m->add()){$this->error('添加失败');}
            if(false === M()->query($sql)){$this->error('添加数据表失败');}
            exit('<script type="text/javascript">alert("添加成功");window.opener.location.reload();window.close();</script>');
        }
        $this->display();
    }
    
    /*
     * 模型修改
     */
    public function edit($id){
        $m = D('Zixunchannel');
        $list = $m->where(array('id'=>$id))->find();
        /*查询是否有这张表*/
        $m2 = M();
        $is_table = $this->is_table($list['tablename']);
        if(IS_POST){            
            if(false === $m->create()){$this->error($m->getError());}  
            if(false === $m->save()){$this->error('修改失败');}            
            if($is_table && $list['tablename'] != I('post.tablename')){$m2->query('rename table '.$list['tablename'].' to '.I('post.tablename'));}
            exit('<script type="text/javascript">alert("修改成功");window.opener.location.reload();window.close();</script>');
        }               
        //查出表字段详细信息
        if($is_table){
            $_fields = $m->query('show full columns from '.$list['tablename']);
            $this->assign('fields',$_fields);
        }        
        $this->assign('list',$list);
        $this->display();
    }
    
    /*
     * 模型删除
     */
    public function del($id){
        $m2 = M('zixuntype');
        if($m2->where(array('channelid'=>$id))->find()){$this->error('本模型下有栏目，不允许删除');}
        exit;
        $m = M('zixunchannel');
        $list = $m->find($id);
        if(false === $m->delete($id)){$this->error('删除模型失败');}        
        /*删除表*/
        $m2 = M();
        if(false === $result = $m2->query('drop table if exists '.$list['tablename'])){$this->error('删除模型表'.$list['tablename'].'失败');}
        $this->success('删除模型成功');
    }
    
    /*
     * -------------------------------------------------------------------
     * 模型字段增加
     */
    public function field_add(){
        $data = I('get.');
        /*接收上个页面传值并验证*/
        if(!preg_match('/^[A-Za-z][A-Za-z0-9]+$/',$data['tablename'])){$this->error('数据表名不合法');}
        if(!preg_match('/^[A-Za-z][A-Za-z0-9]+$/',$data['name'])){$this->error('字段名不合法');}
        if($data['dtype'] == 'img'){$data['dtype'] = 'varchar';}
        if($data['dtype'] == 'varchar' || $data['dtype'] == 'char' || $data['dtype'] == 'int'){
            if(is_zhengshu($data['length'])){$length = '('.$data['length'].')';}else{$this->error('请填写字段长度');}
        }
        if($data['title']){$comment = 'COMMENT "'.$data['title'].'"';}else{$this->error('表单提示文字不能为空');}
        if($data['auto'] && !$data['primary']){$this->error('自增的字段必须设置为主键');}elseif(!$data['auto']){$data['auto'] = ' ';}
        if($data['default']){$default = 'default "'.$data['default'].'"';}
        if($data['primary']){$primary_key = 'primary key';}
        
        /*查询数据库中是否有这张表*/
        $m = M();
        $is_table = $this->is_table($data['tablename']);
        /*查询这张表中是否有这个字段*/
        if($is_table){
            $_fields = $m->query('describe '.$data['tablename']);
            foreach($_fields as $v){
                $fields[] = $v['Field'];
            }
            if(in_array($data['name'],$fields)){$this->error(C('DB_PREFIX').$data['tablename'].' 表中已经存在 '.$data['name'].' 字段');}
        }
        /*如果数据库中有这张表就增加字段，没有就增加表和字段*/
        if($is_table){
            $sql = 'alter table '.$data['tablename'].' add '.$data['name'].' '.$data['dtype'].$length.' '.$data['null'].' '.$default.' '.$comment.' '.$data['auto'].' '.$primary_key;
        }else{
            $sql = 'CREATE TABLE  '.$data['tablename'].' ('.$data['name'].' '.$data['dtype'].$length.'   '.$data['null'].' '.$default.' '.$comment.' '.$data['auto'].' '.$primary_key.') ENGINE = MYISAM';
        }
        if(false === $m->query($sql)){$this->error('添加字段失败');}
        $this->success('添加字段成功');
    }
    
    /*
     * 模型字段修改
     */
    public function field_edit(){
        $data = I('get.');
        /*接收上个页面传值并验证*/
        if(!preg_match('/^[A-Za-z][A-Za-z0-9]+$/',$data['tablename'])){$this->error('数据表名不合法');}
        if(!preg_match('/^[A-Za-z][A-Za-z0-9]+$/',$data['name'])){$this->error('字段名不合法');}
        if($data['dtype'] == 'varchar' || $data['dtype'] == 'char' || $data['dtype'] == 'int'){
            if(is_zhengshu($data['length'])){$length = '('.$data['length'].')';}else{$this->error('请填写字段长度');}
        }
        if($data['title']){$comment = 'COMMENT "'.$data['title'].'"';}else{$this->error('表单提示文字不能为空');}
        if($data['auto'] && !$data['primary']){$this->error('自增的字段必须设置为主键');}elseif(!$data['auto']){$data['auto'] = ' ';}
        if($data['default']){$default = 'default "'.$data['default'].'"';}
        if($data['primary']){$primary_key = 'primary key';}
        
        /*查询数据库中是否有这张表*/
        $m = M();        
        $is_table = $this->is_table($data['tablename']);
        if(!$is_table){$this->error('数据库中不存在 '.$data['tablename'].' 表');}
        /*查询这张表中是否有这个字段*/       
        $_fields = $m->query('describe '.$data['tablename']);
        foreach($_fields as $v){
            $fields[] = $v['Field'];
        }
        if(!in_array($data['name2'],$fields)){$this->error(C('DB_PREFIX').$data['tablename'].' 表中不存在 '.$data['name2'].' 字段');}
        
        $m->query('alter table '.$data['tablename'].' change '.$data['name'].' '.$data['name'].' '.$data['dtype'].$length);
        $m->query('alter table '.$data['tablename'].' drop primary key');
        
        $sql = 'alter table '.$data['tablename'].' change '.$data['name2'].' '.$data['name'].' '.$data['dtype'].$length.' '.$data['null'].' '.$default.' '.$comment.' '.$data['auto'].' '.$primary_key;
        
        if(false === $m->query($sql)){$this->error('修改字段失败');}
        $this->success('修改字段成功');
    }
   
    /*
     * 模型字段删除
     */
    public function field_del(){
        $m = M();
        $data = I('get.');
        $sql = 'alter table '.$data['tablename'].' drop '.$data['field'];
        $result = $m->query($sql);
        if(false === $result){$this->error('删除字段失败');}
        $this->success('删除字段成功');
    }
    
    /*
     * 查询数据库中是否有这张表
     * parame $tablename string
     * return bool
     */
    protected function is_table($tablename){
        /*查询数据库中是否有这张表*/
        $m = M();
        $_tables = $m->query('show tables');
        $datebase = C('DB_NAME');
        foreach($_tables as $v){
            $tables[] = $v['Tables_in_'.$datebase];
        }
        if(in_array(C('DB_PREFIX').$tablename,$tables)){
           return true;
        }
        return false;
    }
    
    
}